package com.example.bootdemo.controller;

import com.example.bootdemo.entity.MyUser;
import com.example.bootdemo.service.UserService;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author MrBird
 */
@RestController
@RequestMapping("user")
public class UserController {
@Resource
    UserService userService;
    @GetMapping("index")
    public Object index(@AuthenticationPrincipal Authentication authentication, HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header, "bearer ");

        return Jwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();
    }

    @GetMapping("list")
    @PreAuthorize("hasAnyAuthority('user:list')")
    public Object  list(){
        List<MyUser> list = this.userService.list();
        return list;

    }

}
